package top.datacluster.basic.algorithm.leetcode;

public class ReversalSingleLinkLeetcode206 {

    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode end = head;
        while (end.next != null){
            end = end.next;
        }
        ListNode temp = head;
        while (temp != end){
            head = head.next;
            temp.next = end.next;
            end.next = temp;
            temp = head;
        }
        return end;
    }

    public static class ListNode{
        int val;

        ListNode next;

        ListNode(int x) { val = x; }
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(0);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        ListNode result = new ReversalSingleLinkLeetcode206().reverseList(node1);
        while (result != null){
            System.out.println(result.val);
            result = result.next;
        }
    }
}
